import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:jet_rails/jr_app/jr_models/jr_activity_model.dart';
import 'package:jet_rails/jr_app/jr_models/jr_user_model.dart';
import 'package:jet_rails/jr_app/jr_views/jr_user/jr_coin_shop_view.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_blur_container.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_buttons.dart';
import 'package:jet_rails/jr_constant/jr_keys.dart';
import 'package:jet_rails/jr_services/jr_apis.dart';
import 'package:jet_rails/jr_services/jr_services.dart';
import 'package:jet_rails/jr_utils/jr_file.dart';
import 'package:jet_rails/jr_utils/jr_logger.dart';
import 'package:jet_rails/jr_utils/jr_media.dart';
import 'package:jet_rails/jr_utils/jr_shared_preferences.dart';
import 'package:jet_rails/jr_utils/jr_snippet.dart';
import 'package:jet_rails/jr_utils/jr_toast.dart';
import 'package:path_provider/path_provider.dart';

class JrHomeController extends GetxController {
  Rx<int> currentSelectedIndex = (-1).obs;
  Map animationControllers = {};
  final postImageList = <String>[].obs;

  // final homeDataMap = {}.obs;

  static const int postCost = 8;
  static const int giftFreeTickets = 2;
  final freeTickets = 0.obs;
  bool get haveFreeTickets => freeTickets.value > 0;

  @override
  onInit() {
    super.onInit();
    checkFreeTickets();
  }

  checkFreeTickets() {
    final freeTicketsSp = JrSP.instance.getInt(JrKeys.kFreeTickets);
    if (freeTicketsSp == null) {
      freeTickets.value = giftFreeTickets;
      JrSP.instance.setInt(JrKeys.kFreeTickets, freeTickets.value);
      Future.delayed(const Duration(seconds: 1), () {
        Get.dialog(buildDialog());
      });
    }
  }

  Widget buildDialog() {
    return Center(
      child: JrBlurContainer(
        height: 270.h,
        width: 320.w,
        padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 20.h),
        decoration: BoxDecoration(
            gradient: const LinearGradient(
                colors: [Color(0x7DF29FFF), Color(0x7DA46EFF)], begin: Alignment.topLeft, end: Alignment.bottomRight),
            borderRadius: BorderRadius.circular(12.r)),
        child: Column(children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Image.asset('assets/webp/icon_coin.webp', height: 44.w),
              SizedBox(width: 7.w),
              Text('X$giftFreeTickets', style: const TextStyle(fontSize: 24).merge(JrSnippets.commonTextStyle))
            ],
          ),
          SizedBox(height: 20.h),
          Expanded(
            child: Text(
              'Thank you for joining our community! As a welcome gift, we will give you two event team tickets. Go find your partners and have a good time together!',
              style: TextStyle(fontSize: 14.sp, color: Colors.white, height: 1.5),
            ),
          ),
          SizedBox(height: 20.h),
          JrStyledButton(
            text: 'OK',
            onTap: () => Get.back(),
          ),
        ]),
      ),
    );
  }

  useFreeTickets() {
    freeTickets.value--;
    JrSP.instance.setInt(JrKeys.kFreeTickets, freeTickets.value);
  }

  refreshActivityList() {
    JrServices.instance.allActivity.refresh();
  }

  void addPostImage() async {
    String? imgPath = await JrMedia.instance.pickImage();
    if (imgPath != null) {
      Directory directory = await getTemporaryDirectory();
      String name = imgPath.split('/').last;
      String destPath = '${directory.path}/article/${JrServices.instance.loginUser.value.userId!}/$name';
      await JrFile.copyFile(imgPath, destPath);
      postImageList.add(destPath);
    }
  }

  void createEvent(String teamName, String description, {String? time, String? place}) async {
    try {
      EasyLoading.show(dismissOnTap: false);
      bool shouldConsumeTicket = false;
      if (haveFreeTickets) {
        shouldConsumeTicket = true;
      } else if ((JrServices.instance.loginUser.value.availableCoins) > postCost) {
        await JrApis.consumeCoins(postCost);
        JrServices.instance.loginUser.value.availableCoins -= postCost;
        JrServices.instance.refreshLoginUser();
      } else {
        Get.to(() => const JrCoinShopView());
        JrToast.show('Coin account is insufficient. You need $postCost coins to publish.');
        return;
      }

      await Future.delayed(const Duration(seconds: 2));

      final my = JrServices.instance.loginUser.value;
      JrActivityModel activityModel = JrActivityModel(
          teamName: teamName,
          time: time,
          place: place,
          description: description,
          author: JrUserModel(
            nickname: my.nickname,
            avatar: my.getAvatarUrl,
            userId: my.userId ?? '',
          ),
          authorCode: '',
          thumbnail: postImageList.value.elementAt(0),
          content: postImageList.value,
          commentList: [],
          attendedUser: 1,
          likedByMe: true,
          joined: true);
      JrServices.instance.allActivity.value.insert(0, activityModel);
      refreshActivityList();
      JrServices.instance.saveActivity();
      if (shouldConsumeTicket) {
        freeTickets.value--;
      }
      Get.back();
      JrToast.show('post successfully');
    } catch (e) {
      JrLogger.e('$e');
    } finally {
      EasyLoading.dismiss();
    }
  }

  void toggleLike(JrActivityModel item) {
    item.likedByMe = !item.likedByMe;
    JrServices.instance.saveActivity();
    refreshActivityList();
  }

  void toggleJoinStatus(JrActivityModel item) {
    if (item.joined) {
      item.joined = false;
      item.attendedUser--;
    } else {
      item.joined = true;
      item.attendedUser++;
    }
    refreshActivityList();
    JrServices.instance.saveActivity();
  }
}
